package tool

import (
	"image/color"

	"github.com/gin-gonic/gin"
	"github.com/mojocn/base64Captcha"
)

type CaptchaReault struct {
	Id           string `json:"id"`
	Base64Blob   string `json:"base_64_blob"`
	VertifyValue string `json:"code"`
}

// 设置自带的 store
var store = base64Captcha.DefaultMemStore

// 生成验证码
func GenerateCaptcha(c *gin.Context) (id, b64s string, err error) {
	var driver base64Captcha.Driver
	var driverString base64Captcha.DriverString

	// 配置验证码信息
	captchaConfig := base64Captcha.DriverString{
		Height:          60,
		Width:           200,
		NoiseCount:      0,
		ShowLineOptions: 2 | 4,
		Length:          4,
		Source:          "23456789qwertyupkhgfdsazxcvbnm",
		BgColor: &color.RGBA{
			R: 3,
			G: 102,
			B: 214,
			A: 125,
		},
		Fonts: []string{"wqy-microhei.ttc"},
	}
	driverString = captchaConfig
	driver = driverString.ConvertFonts()

	// 生成 base64 图片
	captcha := base64Captcha.NewCaptcha(driver, store)

	// 获取
	id, base64Blog, err := captcha.Generate()

	return id, base64Blog, err
}

// 验证 captcha 是否正确
func CaptVerify(id string, capt string) bool {
	// fmt.Println("id:" + id)
	// fmt.Println("capt:" + capt)

	if id == "" || capt == "" {
		return false
	}
	// 第三个参数 true, 同时在内存清理掉这个图片
	return store.Verify(id, capt, true)
}

func GetCaptchaReault(id string, base64Blog string, code string) *CaptchaReault {
	return &CaptchaReault{
		Id:           id,
		Base64Blob:   base64Blog,
		VertifyValue: code,
	}
}
